from fastapi import FastAPI, Form, HTTPException
import pymysql

app = FastAPI()


@app.post("/login")
def dl(name: str = Form(...), pwd: str = Form(...)):
    global conn, cursor
    try:
        # 链接数据库
        conn = pymysql.Connection(user="root", password="Aa1234567.", database="api")
        # 创建游标对象
        cursor = conn.cursor()
        # 执行SQL语句
        cursor.execute("select * from t_user where name =%s and pwd =%s", (name, pwd))
        a = cursor.fetchone()
        if a is None:
            # 失败
            raise HTTPException(404, "登录失败")
        else:
            # 登录成功
            return {"msg": "登录成功"}
    except Exception as e:
        print(e)
        raise
    finally:
        # 关闭资源
        cursor.close()
        conn.close()
